import network
import time

def do_connect(essid, password, timeout=10):
    wlan = network.WLAN(network.STA_IF)  # 设置模式为 STA
    wlan.active(True)  # 启用 WLAN
    if not wlan.isconnected():  # 检查是否已连接
        print('Connecting to network...')
        wlan.connect(essid, password)  # 连接到 Wi-Fi
        start_time = time.time()
        while not wlan.isconnected():
            if time.time() - start_time > timeout:
                print('Connection timeout!')
                return False
            time.sleep(1)
    print('Network config:', wlan.ifconfig())  # 输出连接信息
    return True

# 配置 STA 模式
def setup_sta(essid, password):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    try:
        wlan.scan()  # 扫描可用网络
    except OSError as e:
        print('Wi-Fi scan failed:', e)
        return False
    if not wlan.isconnected():
        if not do_connect(essid, password):
            print('Failed to connect in STA mode.')
            return False
    print('STA mode connected:', wlan.ifconfig())
    return True

# 配置 AP 模式
def setup_ap():
    ap = network.WLAN(network.AP_IF)
    ap.config(essid='ESP-AP', max_clients=10)  # 配置 AP 模式
    ap.active(True)
    print('AP mode activated:', ap.ifconfig())

# 执行连接函数
def wifi(essid,password):
    
    print(essid+"账号"+password+"密码")
    if not setup_sta(essid, password):
        print('STA setup failed.')
    
    setup_ap()

#essid = 'iQOONeo5'  # 替换为你的 Wi-Fi 名称
#password = '20030707Hlm'  # 替换为你的 Wi-Fi 密码
# 运行主函数
#wifi(essid,password)
